import 'package:flutter/foundation.dart';
import 'package:loxen/api/api.dart';
import 'package:loxen/mode/address_list.dart';
import 'package:loxen/mode/address_mode.dart';
import 'package:loxen/mode/base_mode.dart';
import 'package:rxdart/rxdart.dart';

mixin AddressMixin {
  //200
  Stream<int> deleteAddress(String id) {
    return ApiService.deleteAddress(id).flatMap((value) => Stream.value(value.statusCode));
  }

  Stream<List<Address>> getAddressList() {
    return ApiService.getAddress()
        .flatMap((value) => compute(decodeAddressBean, value.data).asStream())
        .flatMap((value) => Stream.value(value?.data?.results));
  }

  Stream<dynamic> getOperationLists(String id) {
    return ApiService.operationLocations(id)
        .flatMap((value) => Stream.value(value.data['data']['results']));
  }

  Stream<Address> getDefaultAddress() {
    return ApiService.getAddress()
        .flatMap((value) => compute(decodeAddressBean, value.data).asStream())
        .flatMap((value) {
      var data = value?.data?.results;
      if (data != null && data.length > 0) {
        return Stream.value(data[0]);
      } else {
        return Stream.value(null);
      }
    });
  }

  //create201   update200
  Stream<int> createOrUpdataAddress(String signerName, String signerMobile, String province,
      String city, String district, String address, bool defaultAddress, String lat, String lng,
      {bool updata = false, String id}) {
    if (updata) {
      return ApiService.upAddress(id, signerName, signerMobile, province, city, district, address,
              defaultAddress, lat, lng)
          .flatMap((value) => Stream.value(value.statusCode));
    } else {
      return ApiService.newAddress(
              signerName, signerMobile, province, city, district, address, defaultAddress, lat, lng)
          .flatMap((value) => Stream.value(value.statusCode));
    }
  }

  static BaseMode<AddressList> decodeAddressBean(dynamic json) {
    return BaseMode<AddressList>(json);
  }
}
